// PongView.m
#import "PongView.h"

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

#import "Common.h"
#import "PongField.h"

NSRect thumbRect;
BOOL pongLeftArrow = NO;
BOOL pongRightArrow = NO;

@implementation PongView

- (id)initWithFrame:(NSRect)aFrame
{
	self = [super initWithFrame:aFrame];
	if (nil != self)
	{
		thumbRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
		field = nil;	
	}
	return self;
}

//- (BOOL)isFlipped
//{
//    return YES;
//}

- (PongField *)field
{
    //NSLog(@"in -field, returned field = %@", field);
    return field; 
}
- (void)setField:(PongField *)aField
{
    //NSLog(@"in -setField:, old value of field: %@, changed to: %@", field, aField);
    if (field != aField) {
        [aField retain];
        [field release];
        field = aField;
    }
}

// so that we can get keyboard events
- (BOOL)acceptsFirstResponder {
     return YES;
}

- (void)setThumbRect:(NSRect) rect
{
	thumbRect = NSMakeRect(rect.origin.x, rect.origin.y, rect.size.height + 10, rect.size.height + 10);
	[self setNeedsDisplay:YES];
}

- (void)setThumbPoint:(NSPoint)aPoint
{
	NSRect aThumbRect = NSMakeRect(aPoint.x, aPoint.y, 10, 10);
	[self setThumbRect:aThumbRect];
}

- (void)mouseUp:(NSEvent *)event
{
	NSRect rect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
	[self setThumbRect:rect];
    [super mouseUp:event];
}

- (void)mouseDown:(NSEvent *)event
{
    [self setThumbPoint:[event locationInWindow]];
    [super mouseDown:event];
}

- (void)keyDown:(NSEvent *)event
{
     NSEventType type = [event type];
     unsigned int flags = [event modifierFlags];
     if(type == NSKeyDown)
     {
        //arrow keys
        if (flags & NSNumericPadKeyMask) 
        {
            NSString *theArrow = [event charactersIgnoringModifiers];
			unichar keyChar = 0;
			
			if ( [theArrow length] == 0 )
				return;            // reject dead keys
			
			if ( [theArrow length] == 1 ) 
				keyChar = [theArrow characterAtIndex:0];
            else
                return;
            if ( keyChar == NSLeftArrowFunctionKey ) 
            {
                pongLeftArrow = YES;
                pongRightArrow = NO;
            }
            if ( keyChar == NSRightArrowFunctionKey )
            {
                pongLeftArrow = NO;
                pongRightArrow = YES;   
            }
        }
     }
}

- (void)keyUp:(NSEvent *)theEvent
{
    pongLeftArrow = NO;
    pongRightArrow = NO;
}

- (void)mouseDragged:(NSEvent *)event
{
    [self setThumbPoint:[event locationInWindow]];
    [super mouseDragged:event];
}

- (BOOL)canBecomeFirstResponder
{
	 return NO;
}

- (void)drawRect:(NSRect)frame
{

    NSColor *everythingIsThisColor = [NSColor greenColor];
    
    [[NSColor blackColor] set];
	NSRectFill(frame);
	
    [everythingIsThisColor set];
	[field drawInRect:[self frame]];
}

@end
